import logging
import xlsxwriter
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from xlwt.compat import xrange
from backend.common.api_response import JsonResponse
from backend.common.common import record_dynamic
from backend.common.common_db import Interface
from backend.models import Lyzd_Interface, Lyzd_Interface_Param, Lyzd_Interface_Header, Lyzd_Interface_Case, \
    Lyzd_Interface_Case_Param, Lyzd_Interface_Case_Check, Sys_Project, Sys_Model
from backend.serializers import Sys_InterfaceSerializer, Sys_CaseSerializer, Lyzd_InterfaceCase_ActionSerializer, \
    Sys_CaseParamSerializer, Sys_CaseCheckSerializer, Lyzd_InterfaceParamSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。



class LyzdCaseList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        case_name = request.GET.get("case_name")
        interfaceID = request.GET.get("interface_id")
        projectID = request.GET.get("project_id")
        project = Sys_Project.objects.filter(status=0)
        model = Sys_Model.objects.filter(status=0)
        api = Lyzd_Interface.objects.filter(project__in=project, model__in=model)
        if case_name:
            if interfaceID:
                # interfaceID 存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__id=interfaceID,
                                                             case_name__contains=case_name, project=projectID,
                                                             case_type__in=(0, 1)).order_by(
                        "delete_flag", "-id")
                else:

                    obi = Lyzd_Interface_Case.objects.filter(interface_id__id=interfaceID,
                                                             case_name__contains=case_name,
                                                             case_type__in=(0, 1)).order_by("delete_flag", "-id")

            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(case_name__contains=case_name,
                                                             interface_id__in=api, project=projectID,
                                                             case_type__in=(0, 1)).order_by("delete_flag", "-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(case_name__contains=case_name,
                                                             interface_id__in=api, case_type__in=(0, 1)).order_by(
                        "delete_flag", "-id")
        else:
            if interfaceID:  # interfaceID 存在
                #           if interfaceID: #interfaceID 存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id=interfaceID, project=projectID,
                                                             case_type__in=(0, 1)).order_by(
                        "delete_flag", "-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id=interfaceID, case_type__in=(0, 1)).order_by(
                        "delete_flag", "-id")

            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__in=api, case_type__in=(0, 1),
                                                             project=projectID).order_by("delete_flag", "-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__in=api, case_type__in=(0, 1)).order_by(
                        "delete_flag", "-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        serialize = Sys_CaseSerializer(obm, many=True)

        # json_data = serializers.serialize("json", obm, ensure_ascii=False)
        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


class LyzdCaseCGList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        case_name = request.GET.get("case_name")
        interfaceID = request.GET.get("interface_id")
        projectID = request.GET.get("project_id")
        project = Sys_Project.objects.filter(status=0)
        model = Sys_Model.objects.filter(status=0)
        api = Lyzd_Interface.objects.filter(project__in=project, model__in=model)
        if case_name:
            if interfaceID:
                # interfaceID 存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__id=interfaceID,
                                                             case_name__contains=case_name, project=projectID,
                                                             case_type='2').order_by(
                        "-id")
                else:

                    obi = Lyzd_Interface_Case.objects.filter(interface_id__id=interfaceID,
                                                             case_name__contains=case_name, case_type='2').order_by(
                        "-id")

            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(case_name__contains=case_name,
                                                             interface_id__in=api, project=projectID,
                                                             case_type='2').order_by("-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(case_name__contains=case_name,
                                                             interface_id__in=api, case_type='2').order_by("-id")
        else:
            if interfaceID:  # interfaceID 存在
                #           if interfaceID: #interfaceID 存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id=interfaceID, project=projectID,
                                                             case_type='2').order_by(
                        "-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id=interfaceID, case_type='2').order_by("-id")

            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__in=api, case_type='2',
                                                             project=projectID).order_by("-id")

                else:
                    obi = Lyzd_Interface_Case.objects.filter(interface_id__in=api, case_type='2').order_by("-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        serialize = Sys_CaseSerializer(obm, many=True)

        # json_data = serializers.serialize("json", obm, ensure_ascii=False)
        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


class AddCase(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):
        try:
            # 校验必传参数

            if not str(data["getCheckTypeFirstID"]) or not str(data["getModelFirstID"]) \
                    or not str(data["getProjectFirstID"]) or not \
                    str(data["getCaseTypeFirstID"]) or not str(data["getApiFirstID"]) \
                    or not str(data["case_name"]) or not str(data["ActionConditionFirstID"]):
                return JsonResponse(code="999996", msg="参数必填校验失败!")


        except KeyError:

            return JsonResponse(code="999996", msg="参数有误3!")

    def post(self, request):

        data = JSONParser().parse(request)

        result = self.parameter_check(data)

        if result:
            return result

        case_name = Lyzd_Interface_Case.objects.filter(case_name=data["case_name"], interface=data["getApiFirstID"])

        if len(case_name):

            return JsonResponse(code="999997", msg="存在相同用例名称!")
        else:
            with transaction.atomic():  # 执行错误后，帮助事物回滚

                serialize = Sys_CaseSerializer(data=data)
                record_dynamic(project=data["getProjectFirstID"],
                               _type="新增", operationObject="用例", user=request.user.username,
                               data="新增用例“%s”" % data["case_name"])
                # getCheckTypeFirstID  2数据校验  1常规校验
                CheckType = data['getCheckTypeFirstID']
                sqlExpect = ""
                sql = ""
                key = ""
                action_condition = ''
                checkType = data["getCheckTypeFirstID"]
                if checkType == 0:  # 走常规校验 response responseArea
                    responseArea = data["responseArea"]
                    key = str(responseArea[0]["key"])
                    sqlExpect = str(responseArea[0]["zhengze"])
                    action_condition = str(data["ActionConditionFirstID"])  # 执行条件 常规校验是下拉选择的

                elif checkType == 1:  # 走数据校验 database
                    sqlArea = data["sqlArea"]
                    sql = str(sqlArea[0]["sql"])
                    sqlExpect = str(sqlArea[0]["sqlExpect"])
                    action_condition = ''  # 走数据校验不存在执行条件
                else:
                    return JsonResponse(code="999990", msg="不存在的校验格式!")

                case_name = data["case_name"]
                check_sql = sql
                check_value = sqlExpect  # 预期值
                check_key = key  # 校验关键字

                create_user = str(request.user.username)
                modify_user = str(request.user.username)
                # check_type 校验分类
                check_type = data["getCheckTypeFirstID"]
                case_type = data["getCaseTypeFirstID"]  # data["interface_name_zh"]
                interface_id = data["getApiFirstID"]
                project_id = data["getProjectFirstID"]

                """
                调用通用方法插入
                action_condition
                
                """

                Interface.addCase(case_name, create_user, modify_user, check_type, case_type, interface_id,
                                  action_condition, project_id)

                """获取用例表id并完成明细表写入操作"""
                # Lyzd_Interface_Case
                caseidMax = Lyzd_Interface_Case.objects.filter(case_name=case_name, interface=data["getApiFirstID"])

                id_new = caseidMax[0].id

                # 写入从表 Lyzd_Interface_Case_Param
                paramList = data["param"]

                for i in paramList:

                    try:
                        param_value = i["content"]
                    except:
                        param_value = ""

                    """进行循环"""
                    # lyzd_interface_param 接口入参表 Lyzd_Interface_Param
                    interface_id = data["getApiFirstID"]  # 获取的是最外层选的接口id
                    # create_user = request.user.username
                    # modify_user = request.user.username
                    param_key = i["param_key"]

                    interface_cases_id = int(id_new)

                    Interface.addCaseParam(interface_id, create_user, modify_user, param_key, param_value,
                                           interface_cases_id)

                if CheckType == 0:  # getCheckTypeFirstID  1数据校验  0常规校验
                    checkList = data["responseArea"]
                    for i in checkList:

                        """进行循环"""
                        # Lyzd_Interface_Header_Param

                        try:
                            check_condition = int(i["_type1"])
                        except:
                            check_condition = "1"
                        interface_cases_id = int(id_new)
                        try:
                            action_condition = int(i["_type2"])
                        except:
                            action_condition = ""  # 1与   2或

                        # create_user = request.user.username
                        # modify_user = request.user.username
                        expect_value = i["zhengze"]
                        check_key = i["key"]

                        check_condition = check_condition
                        """调用接口并存关联表"""

                        Interface.addCaseCheck(expect_value, create_user, modify_user, check_key, check_condition,
                                               interface_cases_id)
                elif CheckType == 1:  # 走数据校验

                    Interface.addCaseCheckDB(sqlExpect, sql, create_user, modify_user, interface_cases_id)
                    """"
                    check_sql = sql,
                    check_value = sqlExpect,  # 预期值
                    check_key = key,  # 校验关键字
                    
                    """

        return JsonResponse(code="999999", msg="成功!")


class EditStatusCase(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):

        """查询条件"""
        # 必传参数
        data = JSONParser().parse(request)

        case_id = tuple(data.values())[0]

        status = Lyzd_Interface_Case.objects.filter(id=case_id)

        flag = status[0].delete_flag

        if flag == '0' or flag == False:
            Lyzd_Interface_Case.objects.filter(id=case_id).update(
                delete_flag=1
            )
            return JsonResponse(code="999999", msg="禁用成功")
        elif flag == '1' or flag == True:
            Lyzd_Interface_Case.objects.filter(id=case_id).update(
                delete_flag=0
            )
            return JsonResponse(code="999999", msg="启用成功")


class CaseInfo(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        # project_id = request.GET.get("project_id")
        """
        获取接口详细信息
        :param request:
        :return:
        """

        cid = request.GET.get("case_id")

        try:

            obm = Lyzd_Interface_Case.objects.filter(id=cid)

            serializer = Sys_CaseSerializer(obm, many=True)
            # serialize = Sys_InterfaceSerializer(obm, many=True)

            obm1 = Lyzd_Interface_Case_Check.objects.filter(interface_cases=cid)

            serializer1 = Sys_CaseCheckSerializer(obm1, many=True)

            obm2 = Lyzd_Interface_Case_Param.objects.filter(interface_cases=cid)

            serializer2 = Sys_CaseParamSerializer(obm2, many=True)



        except ObjectDoesNotExist:
            pass
        return JsonResponse(data={'case': serializer.data, 'check': serializer1.data,

                                  'param': serializer2.data}, code="999999", msg="成功！")


class CaseEdit(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):

        """
        校验参数
        :param data:
        :return:
        """

        try:
            # 校验必传参数
            if not data["cid"]:
                return JsonResponse(code="999996", msg="参数必填校验失败!")

        except KeyError:
            return JsonResponse(code="999996", msg="参数不全!")

    def post(self, request):
        """
        新增接口
        :param request:
        :return:
        """

        data = JSONParser().parse(request)

        result = self.parameter_check(data)

        if result:
            return result
        with transaction.atomic():  # 执行错误后，帮助事物回滚

            # serialize = Sys_CaseSerializer(data=data)
            cid = data["cid"]

            """
                    处理参数未修改或部分修改时时，主表的修改
                    1 check_type  getCheckTypeFirstID
                    2 case_pye    getCaseTypeFirstID
                    3 interface_id   getApiFirstID
                    4 project_id getProjectFirstID
                    5 action_condition ActionConditionFirstID
                    """

            check_type = data["getCheckTypeFirstID"]

            case_type = data["getCaseTypeFirstID"]

            interface_id = data["getApiFirstID"]

            project_id = data["getProjectFirstID"]

            action_condition = data["ActionConditionFirstID"]

            if check_type is not None:
                Lyzd_Interface_Case.objects.filter(id=cid).update(
                    check_type=check_type
                )
            if case_type is not None:
                Lyzd_Interface_Case.objects.filter(id=cid).update(
                    case_type=case_type
                )
            if interface_id is not None:

                """
                判断是不是传来的名字，如果是需要处理
                """
                try:
                    api = Lyzd_Interface.objects.filter(id=interface_id)

                    if len(api) == 0:

                        """网页端未修改用例，传来的是名字，从case表取出关联的interface_id并更新"""
                        case = Lyzd_Interface_Case.objects.filter(id=cid)

                        case_interface = case[0].interface_id

                        interface_id = case_interface

                    else:
                        Lyzd_Interface_Case.objects.filter(id=cid).update(interface=interface_id)
                except:
                    return JsonResponse(code="999996", msg="更新用例关联接口失败")

            if project_id is not None:
                Lyzd_Interface_Case.objects.filter(id=cid).update(
                    project=project_id
                )

            if action_condition != '' or action_condition is not None:
                Lyzd_Interface_Case.objects.filter(id=cid).update(
                    action_condition=action_condition
                )

            """
            更新param表
            1 未勾选接口名称  获取接口id  删除+新增
            2 勾选接口名称   根据传参    删除+新增
            
            """
            if interface_id is None:
                case = Lyzd_Interface_Case.objects.filter(id=cid)

                case_interface = case[0].interface_id

                interface_id = case_interface

            # 删除param表
            Lyzd_Interface_Case_Param.objects.filter(interface_cases=cid).delete()

            # 写入从表 Lyzd_Interface_Case_Param
            paramList = data["param"]

            for i in paramList:

                try:
                    param_value = i["param_value"]
                except:
                    param_value = ""

                """进行循环"""
                # lyzd_interface_param 接口入参表 Lyzd_Interface_Param
                interface_id = interface_id
                # create_user = request.user.username
                # modify_user = request.user.username
                param_key = i["param_key"]

                interface_cases_id = cid
                create_user = str(request.user.username)
                modify_user = str(request.user.username)

                Interface.addCaseParam(interface_id, create_user, modify_user, param_key, param_value,
                                       interface_cases_id)

            """删除并更新check表"""
            Lyzd_Interface_Case_Check.objects.filter(interface_cases=cid).delete()

            if check_type == 0:  # getCheckTypeFirstID  1数据校验  0常规校验
                checkList = data["responseArea"]
                for i in checkList:

                    """进行循环"""
                    # Lyzd_Interface_Header_Param

                    try:
                        check_condition = int(i["check_condition"])
                    except:
                        check_condition = "1"
                    interface_cases_id = cid
                    try:

                        expect_value = i["expect_value"]
                        check_key = i["check_key"]
                    except:
                        return JsonResponse(code="999997", msg="校验参数不完整")

                    check_condition = check_condition
                    """调用接口并存关联表"""

                    Interface.addCaseCheck(expect_value, create_user, modify_user, check_key, check_condition,
                                           interface_cases_id)
            elif check_type == 1:  # 走数据校验

                checkSqlList = data["sqlArea"]
                for j in checkSqlList:
                    sql = j["check_sql"]
                    sqlExpect = j["expect_value"]

                    Interface.addCaseCheckDB(sqlExpect, sql, create_user, modify_user, interface_cases_id)

        return JsonResponse(code="999999", msg="成功!")


# 用例模板下载
class DownloadCG(APIView):  # 常规
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()
    def get(self, request):
        interface_id = request.GET.get('interface_id')
        project_id = request.GET.get('project_id')

        """
        获取Api下载文档路径
        :param request:
        :return:
        """
        # 调用模板下载方法，成功返回模板路径，失败返回模板下载失败

        try:
            template = CG_template_download(project_id, interface_id)

            if template == '模板下载失败':

                return JsonResponse(code="999997", msg="下载失败")
            else:

                return JsonResponse(code="999999", msg="下载成功", data=template)
            # return JsonResponse(data={'code': '999999', 'msg': '下载成功', 'data': template})
        except:
            return JsonResponse(code="999997", msg="下载失败")


def CG_template_download(project_id, interface_id):
    randomName = 'normal'
    path = "./backend/excel_value/temp/"
    fileName = '%s.xlsx' % (randomName)
    filePath = path + '%s.xlsx' % (randomName)
    workbook = xlsxwriter.Workbook(filePath)
    # 新建一个worksheet
    worksheet = workbook.add_worksheet()
    """样式文件开始"""
    merge_format = workbook.add_format({
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#D3EE5F",
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
        # 'fg_color': '#D7E4BC',  # 颜色填充
    })
    merge_format2 = workbook.add_format({  # 左上角基础数据
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#FABF8F",
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
    })
    merge_format3 = workbook.add_format({  # 小数点校验-3
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#ECDFD3",
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
    })
    merge_format4 = workbook.add_format({  # 边界值校验-2
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#808080",
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
    })
    merge_format5 = workbook.add_format({  # 接口名称颜色
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#91FFFF",  #
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
    })
    merge_format6 = workbook.add_format({  # 接口名称颜色
        # 'bold': True,
        # 'border': 1,
        "fg_color": "#DAEEF3",
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'text_wrap': 1
    })
    """样式文件结束"""

    interface_name = Lyzd_Interface.objects.values('interface_name_zh').get(id__exact=interface_id)
    interface_name = interface_name['interface_name_zh']

    worksheet.write('A3', interface_name)
    param_key = Lyzd_Interface_Param.objects.values('param_key', 'param_type').filter(interface_id__exact=interface_id)

    len_pk = len(param_key)
    len_wz = 2 + len_pk

    endWz = str('A' + str(len_wz))  # 接口名称合并单元格

    youEndWz = str('O' + str(len_wz))
    worksheet.set_column('A:O', 20)
    worksheet.merge_range('A3:' + endWz, interface_name)
    list_api = []

    # 入参类型
    list_type = []

    for a in range(0, len(param_key)):
        list_api.append(param_key[a]['param_key'])
        list_type.append(param_key[a]['param_type'])

    tup_api = tuple(list_api)
    tup_type = tuple(list_type
                     )

    worksheet.write_column('B3', tup_api, merge_format6)
    worksheet.write_column('C3', tup_type, merge_format6)

    first_row = 0
    first_col = 0
    rows_count = len_wz
    cols_count = 15

    Drawbord = draw_frame_border(workbook, worksheet, first_row, first_col, rows_count, cols_count)
    worksheet.merge_range('A1:A2', '接口名称', merge_format)
    worksheet.merge_range('B1:B2', '接口入参', merge_format)
    worksheet.merge_range('C1:C2', '数据类型', merge_format)
    worksheet.merge_range('D1:D2', '必填校验-1(是=必填=1，否=选填=0)', merge_format)
    worksheet.merge_range('E1:E2', '预期key', merge_format)
    worksheet.merge_range('F1:F2', '条件', merge_format)
    worksheet.merge_range('G1:G2', '值', merge_format)
    worksheet.merge_range('H1:N1', '边界值校验-2', merge_format4)
    worksheet.merge_range('O1:O2', '小数点位数校验-3', merge_format3)
    worksheet.write('H2', '最大值', merge_format2)
    worksheet.write('I2', '>= 或>是否包含最大值（包含：0，不包含：1）', merge_format2)
    worksheet.write('J2', '最小值', merge_format2)
    worksheet.write('K2', '＜= 或＜是否包含最小值（包含：0，不包含：1）', merge_format2)
    worksheet.write('L2', '预期key', merge_format2)
    worksheet.write('M2', '条件', merge_format2)
    worksheet.write('N2', '值', merge_format2)

    worksheet.merge_range('A3:' + endWz, interface_name, merge_format5)

    # worksheet.merge_range('A1:'+youEndWz, 'Merged Cells', merge_format)

    workbook.close()
    return filePath


def add_to_format(existing_format, dict_of_properties, workbook):
    """Give a format you want to extend and a dict of the properties you want to
    extend it with, and you get them returned in a single format"""
    new_dict = {}
    for key, value in existing_format.__dict__.iteritems():
        if (value != 0) and (value != {}) and (value != None):
            new_dict[key] = value
    del new_dict['escapes']

    return (workbook.add_format(dict(new_dict.items() + dict_of_properties.items())))


def box(workbook, sheet_name, row_start, col_start, row_stop, col_stop):
    """Makes an RxC box. Use integers, not the 'A1' format"""

    rows = row_stop - row_start + 1
    cols = col_stop - col_start + 1

    for x in xrange((rows) * (cols)):  # Total number of cells in the rectangle

        box_form = workbook.add_format()  # The format resets each loop
        row = row_start + (x // cols)
        column = col_start + (x % cols)

        if x < (cols):  # If it's on the top row
            box_form = add_to_format(box_form, {'top': 1}, workbook)
        if x >= ((rows * cols) - cols):  # If it's on the bottom row
            box_form = add_to_format(box_form, {'bottom': 1}, workbook)
        if x % cols == 0:  # If it's on the left column
            box_form = add_to_format(box_form, {'left': 1}, workbook)
        if x % cols == (cols - 1):  # If it's on the right column
            box_form = add_to_format(box_form, {'right': 1}, workbook)

        sheet_name.write(row, column, "", box_form)


def draw_frame_border(workbook, worksheet, first_row, first_col, rows_count, cols_count):
    # top left corner
    worksheet.conditional_format(first_row, first_col,
                                 first_row, first_col,
                                 {'type': 'formula', 'criteria': 'True',
                                  'format': workbook.add_format({'top': 1, 'left': 1})})
    # top right corner
    worksheet.conditional_format(first_row, first_col + cols_count - 1,
                                 first_row, first_col + cols_count - 1,
                                 {'type': 'formula', 'criteria': 'True',
                                  'format': workbook.add_format({'top': 1, 'right': 1})})
    # bottom left corner
    worksheet.conditional_format(first_row + rows_count - 1, first_col,
                                 first_row + rows_count - 1, first_col,
                                 {'type': 'formula', 'criteria': 'True',
                                  'format': workbook.add_format({'bottom': 1, 'left': 1})})
    # bottom right corner
    worksheet.conditional_format(first_row + rows_count - 1, first_col + cols_count - 1,
                                 first_row + rows_count - 1, first_col + cols_count - 1,
                                 {'type': 'formula', 'criteria': 'True',
                                  'format': workbook.add_format({'bottom': 1, 'right': 1})})

    # top
    worksheet.conditional_format(first_row, first_col + 1,
                                 first_row, first_col + cols_count - 2,
                                 {'type': 'formula', 'criteria': 'True', 'format': workbook.add_format({'top': 1})})
    # left
    worksheet.conditional_format(first_row + 1, first_col,
                                 first_row + rows_count - 2, first_col,
                                 {'type': 'formula', 'criteria': 'True', 'format': workbook.add_format({'left': 1})})
    # bottom
    worksheet.conditional_format(first_row + rows_count - 1, first_col + 1,
                                 first_row + rows_count - 1, first_col + cols_count - 2,
                                 {'type': 'formula', 'criteria': 'True', 'format': workbook.add_format({'bottom': 1})})
    # right
    worksheet.conditional_format(first_row + 1, first_col + cols_count - 1,
                                 first_row + rows_count - 2, first_col + cols_count - 1,
                                 {'type': 'formula', 'criteria': 'True', 'format': workbook.add_format({'right': 1})})

def webservice_case(x):
    case = Lyzd_Interface_Case.objects.get(id=x)
    # print(case.case_name)
    # print("环境信息拼接为%s" % environment_data)
    return 1
